      Program SPH_Turb
      ! SPH simulation for homogeneous isotropic turbulence
      ! Created: June 09, 2011  Le FANG @ Hamburg, Germany

      include "param.fi"
      include "common.fi"

      Integer I,J, I1,I2,I3
      Integer FNUM_Stat, IfStart

      ! Initialization
      Call Initial

      ! Read INI file
      Call READINI

      ! Initial Field
      Call INITSTATE
      If (ifDual) Call DualInit

      ! Test HASHINDEX
      !Do I = 1, GRIDNUM*GRIDNUM*GRIDNUM
      !  Call HASHINDEX13(I, I1,I2,I3)
      !  Call HASHINDEX31(I1,I2,I3, J)
      !  If (I.NE.J) Write(*,*) I, J, I1, I2, I3
      !Enddo
      
      ! Development
      Write (*,*) "Start to develop ..."
      Call BORROW_FREEFILE(FNUM_Stat)
      Open(FNUM_Stat, FILE="stat.dat")
      IfStart = 0
      iSTEPOut = 1
      Do While (T .LE. TMAX)
        Call InitHash

        DT = DT0
        CALL STATISTICS(FNUM_Stat)

        iSTEP = INT(STEP)
        Write (*,1233) iSTEP, T, UMax, PMax, ENER, PTTL
        Write (FNUM_Stat,1233) iSTEP, T, UMax, PMax, ENER, PTTL

        If ((MOD(iSTEP,STEPOUT) .EQ. 0 .OR. iSTEP.EQ.1 )
     &      .AND. IfStart .EQ. 1) Then
          !CALL RESULTS
          Call H5PartOutput
          iSTEPOut = iSTEPOut + 1
        Endif

        If (STEPFILT .GT. 0) Then
        If ((MOD(iSTEP,STEPFILT) .EQ. 0 .OR. iSTEP.EQ.1 )
     &      .AND. IfStart .EQ. 1) Then
          Call AVER(Rho, Temp1)
          Do I = 1, NTOT3T
            Rho(I) = Temp1(I)
          Enddo
        Endif
        Endif

        If (TIME_INT .EQ. TIEuler) Then
          If (tagBoundary .EQ. BdrPeriodic) Then
            CALL EULER
          Else IF (tagBoundary .EQ. BdrGhost) Then
            CALL EULER_Ghost
          Endif
        Else IF (TIME_INT .EQ. TIRK4) Then
          CALL RK4
        Endif

        T = T + DT
        STEP = STEP + 1
        IfStart = 1
      Enddo
      Close(FNUM_Stat)
      Call RETURN_FREEFILE(FNUM_Stat)
1233  Format(I6,20E18.8)

      End
C==================================================================
      Subroutine Initial

      include "param.fi"
      include "common.fi"

      INTEGER I
      Do I = 1, 99
        FREESIGN(I) = 0
      Enddo

      T = 0.0

      End Subroutine
C==================================================================
      Subroutine READINI

      include "param.fi"
      include "common.fi"

      INTEGER FNUM
      Call BORROW_FREEFILE(FNUM)
      Open (FNUM, FILE="turb.ini")
      Read (FNUM,*) InitFileName
      Read (FNUM,*) IfContinue
      Read (FNUM,*) NU
      Close (FNUM)
      Call RETURN_FREEFILE(FNUM)
      
      End Subroutine
C==================================================================
